package com.zq.assistant.func.apifactory.handler;

import com.zq.assistant.func.apifactory.api.LifeCycle;
import com.zq.assistant.func.apifactory.api.LifeCycleBinderImpl;
import com.zq.assistant.func.apifactory.invocationhandler.HttpRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by zhangqiang on 17-7-14.
 */

public abstract class BaseOKHttpRequestHandler<R> implements HttpRequestHandler,LifeCycle<R> {

    private Object tag;

    @Override
    public R bindLifeCycle(LifeCycle lifeCycle) {

        Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{LifeCycle.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object returnValue = method.invoke(lifeCycle,args);
                method.invoke(LifeCycleBinderImpl.this.lifeCycle,args);
                return returnValue;
            }
        });
    }

    @Override
    public void onLifeStart() {



    }

    @Override
    public void onLifeStop() {
        cancel();
    }

    @Override
    public Object onHandleHttpRequest(HttpRequest httpRequest) {
        tag = httpRequest.getTag();
        if(tag == null){
            tag = this;
        }


        return null;
    }

    public Object getTag() {
        return tag;
    }
}
